package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ThreadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.检查参数（分页，是否登录）
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_ADMIND,"您尚未登录，请登录！");
        }
        //2.封装各种查询参数
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        //2.1关键字模糊查询
        queryWrapper.like(StringUtils.isNoneBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        //2.2频道查询
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getTitle,dto.getChannelId());
        //2.3状态查询
         queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        //2.4大于等于开始时间
         queryWrapper.ge(dto.getBeginPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate());
        //2.5小于等于结束时间
        queryWrapper.le(dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getEndPubDate());
        //2.6当前登录用户
        queryWrapper.eq(WmNews::getUserId,user.getId());
        //2.7按照发布时间进行降序
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        //2.8分页查询
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmNews> page1 = this.page(page, queryWrapper);
        //3.执行查询并封装查询结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal());
        responseResult.setData(page1.getRecords());
        //4.将图片前缀访问路径设置到host属性中
        responseResult.setHost(webSite);
        return responseResult;

    }

    @Autowired
    KafkaTemplate<String,String>kafkaTemplate;


    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //1.检查参数 封装wmNews对象
        //1.1检查参数（内容，状态，是否登录）
        if (StringUtils.isBlank(wmNewsDto.getContent())) {
           CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"内容不能为空！");
        }
        Short status = wmNewsDto.getStatus();
        if (status==null ||status.intValue()!=0 && status.intValue()!=1){
           CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章状态错误！");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_ADMIND,"您尚未登录，请登录！");
        }
        //1.2基于dto创建wmNews对象（采用属性拷贝的方法）
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);//实现属性拷贝
        //1.3如果type的值为-1，则此时将type的值设置为null,以避免保存出错
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //1.4如果传入的集合images不为空的话，则转为字符串并且用逗号进行拼接
        if (CollectionUtils.isNotEmpty(wmNewsDto.getImages())) {
            String imageStr = wmNewsDto.getImages().stream()
                    .map(str -> str.replaceAll(webSite, ""))
                    .collect(Collectors.joining(","));
            wmNews.setImages(imageStr);
        }
        wmNews.setUserId(user.getId());


        //2.保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //3.如果是待审核状态，需要保存内容图片和封面图片与素材的关联关系（根据状态进行判断）
        if (status==0){//此时表示是草稿状态
          return ResponseResult.okResult();
        }
        //3.1抽取内容中所有的图片
         List<String> contentImages = parseContentImage(wmNewsDto.getContent());
        //3.2保存内容图片与素材的关联关系
        if (CollectionUtils.isNotEmpty(contentImages)) {
            saveRaleticInfo(contentImages,wmNews.getId(),0);
        }
        //3.3保存封面图片与素材的关联关系
        saveRelativeInfoForCover(contentImages,wmNews,wmNewsDto);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("newsId",wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        log.info("文章自动审核消息 已成功发送 文章id：{}",wmNews.getId());


        return ResponseResult.okResult();

    }


    /**
     *
     * @param contentImages
     * @param wmNews
     * @param wmNewsDto
     */

    private void saveRelativeInfoForCover(List<String> contentImages, WmNews wmNews, WmNewsDto wmNewsDto) {
        List<String> images = wmNewsDto.getImages();//封面的图片列表
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (CollectionUtils.isEmpty(contentImages)){
                //如果内容url为空，设置为无图模式
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images=null;
            }else if (contentImages.size()<=2){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images=contentImages.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=contentImages.stream().limit(3).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(images)){

            }
            updateById(wmNews);
        }
        if (CollectionUtils.isNotEmpty(images)){
            images.stream().map(url-> url.replaceAll(webSite,"")).collect(Collectors.toList());

            saveRaleticInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }


    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     *
     * @param materialUrls 相关素材 url集合
     * @param newsId  文章id
     * @param type 0表示内容中引用的素材  1 表示封面引用的素材
     */

    private void saveRaleticInfo(List<String> materialUrls, Integer newsId, int type) {
      //1.查询 素材url集合 所对应的所有的素材信息
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materialUrls)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
        );
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"引用的素材不存在！");
        }
      //2.将素材信息集合 转化为map结合 key:url  value:id
        Map<String, Integer> urlAndMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        //3.遍历素材url集合，将每个url所对应的id存入到素材集合中
        List<Integer> materialId = new ArrayList<>();
        materialUrls.forEach(url->{
            if (!urlAndMap.containsKey(url)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"引用的素材不存在！");
            }
            materialId.add(urlAndMap.get(url));
        });
        //4.调用mapper 批量插入方法 id集合 newsId  type
        wmNewsMaterialMapper.saveRelations(materialId,newsId,(short)type);



    }

    /**
     * 抽取文章内容中所包含的图片，去除前缀的那种
     * @param content
     * @return
     */

    private List<String> parseContentImage(String content) {
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);
        //过滤键是image的那个
        List<String> imageList = contentMap.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.toList());
        return imageList;

    }


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //1.补全信息
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);
        //2.如果id为空则表明原本的数据库中没有这篇文章则表明执行的操作是保存
        if (wmNews.getId()==null) {
            save(wmNews);
        }
        else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
         updateById(wmNews);
        }

    }
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.检查参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据从前端传过来的id的值，查询文章
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章信息不存在！");
        }
        //将查到的的数据返回给前端
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult deleteWmNewsById(Integer id) {
        //1.检查参数
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请选择你要删除的文章！");
        }
        //2.根据从前端传过来的id的值查询文章
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在！");
        }
        //判断文章的状态是否等于9且是否上架
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该文章已发布并且处于上架状态，不能删除！");
        }
        //删除该篇文章并且要删除文章和素材的关联关系表中的那条记录
        removeById(id);
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));

        return ResponseResult.okResult();
    }

    /**
     * 设置文章的上下架功能主要是设置文章的enable这个字段对应的值
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
     //1.检查参数（主要是检查id的值和enable的值）
     if (dto.getId()==null || dto.getEnable()==null){
         CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
     }
        Short enable = dto.getEnable();
     if (enable.intValue()!=0 && enable.intValue()!=1){
         CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架的状态错误！");
     }
     //2.根据文章的id查询文章的信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在！");
        }
     //检查文章的状态的值是否为9（9表示是发布状态，不是发布状态的文章是不允许进行上下架操作的）
     if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)){
         CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前文章不是发布状态，不允许进行上下架操作！");
     }
     wmNews.setEnable(enable);
     updateById(wmNews);
     return ResponseResult.okResult();

    }

}
